package com.logic.landseaserver.task;

import com.logic.landseaserver.common.enums.MeterTypeEnum;
import com.logic.landseaserver.common.util.DateUtil;
import com.logic.landseaserver.service.IMeter;
import com.logic.landseaserver.service.IScheduleService;
import com.logic.landseaserver.ws.request.AchieveDayFreezeEnergyReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

@Component
public class MeterTask {

    private static final Logger log = LoggerFactory.getLogger(MeterTask.class);

    @Autowired
    private IMeter meterService;

    @Autowired
    private IScheduleService iScheduleService;

    @Scheduled(cron = "0 0 1 * * ?")
    public void batchInsert() {
        log.info("每天凌晨1点批量插入水电数据 start");
        try {
            if ("01".equals(DateUtil.getInstence().getDd(new Date()))) {
                return;
            }
            boolean cuteFlag = iScheduleService.cuteSchedule();
            if (cuteFlag) {
                AchieveDayFreezeEnergyReq param = new AchieveDayFreezeEnergyReq();
                if ("02".equals(DateUtil.getInstence().getDd(new Date()))) {
                    param.setDateFrom(DateUtil.getInstence().convertDate(DateUtil.getInstence().getAppointDay(Calendar.DAY_OF_MONTH, -4)));
                } else {
                    param.setDateFrom(DateUtil.getInstence().convertDate(DateUtil.getInstence().getAppointDay(Calendar.DAY_OF_MONTH, -3)));
                }
                param.setDateTo(DateUtil.getInstence().convertDate(DateUtil.getInstence().getAppointDay(Calendar.DAY_OF_MONTH, -2)));
                param.setMeterType(MeterTypeEnum.electricity.getCode());
                meterService.batchInsertFeeDetail(param);
            }

        } catch (Exception e) {
            log.warn("每天凌晨1点批量插入水电数据 error:" + e.getMessage());
        }
        log.info("每天凌晨1点批量插入水电数据 end");

    }

    /**
     * 每天晚上8点批量修正水电数据
     */
    @Scheduled(cron = "0 0 20 * * ?")
    public void batchUpdateFeeDetail() {
        log.info("每天晚上8点批量修正水电数据 start");
        try {
            boolean cuteFlag = iScheduleService.cuteSchedule();
            if (cuteFlag) {
                meterService.batchUpdateMeterData();
            }
        } catch (Exception e) {
            log.info("每天晚上8点批量修正水电数据 error:" + e);
            e.printStackTrace();
        }
    }

}